package com.zhuliwei.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zhuliwei.constants.SystemConstants;
import com.zhuliwei.domain.ResponseResult;
import com.zhuliwei.domain.dto.ChangeUserStatusDto;
import com.zhuliwei.domain.dto.UserAddDto;
import com.zhuliwei.domain.dto.UserDto;
import com.zhuliwei.domain.dto.UserUpdateDto;
import com.zhuliwei.domain.entity.User;
import com.zhuliwei.domain.vo.PageVo;
import com.zhuliwei.domain.vo.UserDataVo;
import com.zhuliwei.domain.vo.UserListVo;
import com.zhuliwei.enums.AppHttpCodeEnum;
import com.zhuliwei.exception.SystemException;
import com.zhuliwei.service.UserService;
import com.zhuliwei.utils.BeanCopyUtils;
import com.zhuliwei.utils.WebUtils;
import io.swagger.annotations.Api;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户管理接口控制层
 *
 * @author 朱力维
 * @time 2022/10/28 11:20
 **/
@RestController
@RequestMapping("/system/user")
@Api(tags="用户",description = "用户管理相关接口")
public class UserController {
    @Resource
    private UserService userService;
    @GetMapping("/list")
    @PreAuthorize("@ps.hasPermission('system:user:list')")
    public ResponseResult<PageVo> list(Integer pageNum, Integer pageSize, UserDto userDto){
        return userService.userPageList(pageNum,pageSize,userDto);
    }
    @GetMapping("/userData")
    public ResponseResult userData(){
        LambdaQueryWrapper<User> adminCondition = new LambdaQueryWrapper<>();
        adminCondition.eq(User::getType, SystemConstants.TYPE_ADMIN);
        Long adminCount = userService.count(adminCondition);
        UserDataVo userDataVo = new UserDataVo();
        userDataVo.setAdminNum(adminCount.intValue());
        LambdaQueryWrapper<User> userCondition = new LambdaQueryWrapper<>();
        userCondition.eq(User::getType, SystemConstants.TYPE_USER);
        Long userCount = userService.count(userCondition);
        userDataVo.setUserNum(userCount.intValue());
        return ResponseResult.okResult(userDataVo);
    }

    @PostMapping
    @PreAuthorize("@ps.hasPermission('system:user:add')")
    public ResponseResult add(@RequestBody UserAddDto userAddDto){
        return userService.add(userAddDto);
    }

    @DeleteMapping("/{ids}")
    @PreAuthorize("@ps.hasPermission('system:user:delete')")
    public ResponseResult delete(@PathVariable List<String> ids){
        return userService.delete(ids);
    }

    @GetMapping("/{id}")
    @PreAuthorize("@ps.hasPermission('system:user:list')")
    public ResponseResult detail(@PathVariable String id){
        return userService.detail(id);
    }

    @PutMapping
    @PreAuthorize("@ps.hasPermission('system:user:update')")
    public ResponseResult update(@RequestBody UserUpdateDto userDto){
        return userService.updateUser(userDto);
    }

    @GetMapping("/export")
    @PreAuthorize("@ps.hasPermission('system:user:export')")
    public void export(HttpServletResponse response){
        try {
            //设置下载文件的请求头
            WebUtils.setDownLoadHeader("用户.xlsx",response);
            //获取需要导出的数据
            List<User> users = userService.list();
            List<UserListVo> userListVos = BeanCopyUtils.copyBeanList(users, UserListVo.class);
            //把数据写入到Excel中
            EasyExcel.write(response.getOutputStream(), UserListVo.class).autoCloseStream(Boolean.FALSE).sheet("用户导出")
                    .doWrite(userListVos);

        } catch (Exception e) {
            //如果出现异常也要响应json
            ResponseResult result = ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
            WebUtils.renderString(response, JSON.toJSONString(result));
        }
    }

    @PutMapping("/changeStatus")
    @PreAuthorize("@ps.hasPermission('system:user:status')")
    public ResponseResult changeStatus(@RequestBody ChangeUserStatusDto userDto){
        if (userDto.getUserId().equals("1535f63ffb3748dba254483725ddda1c")) {
            throw new SystemException(AppHttpCodeEnum.ADMIN_STOP_ERROR);
        }
        User user = userService.getById(userDto.getUserId());
        user.setStatus(userDto.getStatus());
        userService.updateById(user);
        return ResponseResult.okResult();
    }

    // 根据用户名搜索用户
    @GetMapping("/search/{userName}")
    public ResponseResult search(@PathVariable String userName){
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getType,SystemConstants.TYPE_USER);
        lqw.like(User::getUserName,userName);
        lqw.select(User::getId,User::getUserName);
        List<User> list = userService.list(lqw);
        return ResponseResult.okResult(list);
    }
}
